﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using EzDesk.Apps.Interface.Message;
using EzDesk.Apps.Model.Message;
using EzDesk.Apps.ServiceImpl.Message;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using EzDesk.Core.ServiceImpl.Services;
using EzDesk.Utility;

using EzDesk.Utility.Web.Extensions;
using System.Linq;
using EzDesk.Utility.ServiceStatusInfo;

namespace EzDesk.ServiceHost.Controllers
{
    [EzAuthorize]
    public class MessageController : EzDeskAppController
    {
        private readonly ICoreAppService _coreAppService = new CoreAppService();
        private readonly ITopicService _topiService = new TopicService();
        ITopicService TopicService
        {
            get { return _topiService; }
        }

        private const string ReplyRequired = "回复内容不能为空！";
        private const string ReplySuccess = "回复成功";
        private const string CreateSuccess = "新信件发送成功！";
        private const string SendMsgFailed = "信件发送失败！！";
        private const string ConfirmMsgSuccess = "信件确认成功！";
        private const string ConfirmMsgFailed = "确认信件失败！！";
        private const string ReplyMsgFailed = "回复信件失败！！";
        private const string ExceptionType = "[DesktopWeb - Message]";
        private const string MsgContentRequired = "新信件不能为空！";

        #region [Page Method]

        //
        // GET: /Message/Send

        
        public ActionResult Send()
        {
            return View();
        }

        //
        // GET: /Message/Show

        
        public ActionResult Show(Guid topicId)
        {

            Topic topic = TopicService.GetFullTopic(topicId, CurrentUserId).Result;

            var replyListModel = new List<object>();
            var isDisplayConfirmNow =
                CurrentUserId != topic.SenderId &&  //发送者不为本人
                !topic.HasConfirmedBy(CurrentUserId).GetValueOrDefault(true); //还没有确认

            var isDisplayHasConfirmed =
                CurrentUserId != topic.SenderId &&  //发送者不为本人
                topic.HasConfirmedBy(CurrentUserId).GetValueOrDefault(false); //已经确认

            topic.ReplyList.Foreach(p => replyListModel.Add(
                new
                {
                    p.CreateOn,
                    SenderUser = _coreAppService.GetSimpleUserById(p.SenderId),
                    p.MessageId,
                    Text = p.MessageText,
                }));

            var participator = getParticipatorInfo(topic);
            var confirmNameList =
                topic.MessageInbox.Where(mi => mi.ConfirmOn != null).Select(
                    mi => _coreAppService.GetSimpleUserById(mi.UserId));

            var noConfirmNameList =
                topic.MessageInbox.Where(mi => mi.ConfirmOn == null).Select(
                    mi => _coreAppService.GetSimpleUserById(mi.UserId));

            ViewData["Message"] = new
            {
                Id = topic.MessageId,
                topic.NeedConfirm,
                HasConfirmed = topic.HasConfirmedBy(CurrentUserId),
                SenderUser = _coreAppService.GetSimpleUserById(topic.SenderId),
                topic.CreateOn,
                Title = topic.MessageTitle,
                Text = topic.MessageText,
                Participator = participator,
                NotConfirmNameList = noConfirmNameList,
                ConfirmNameList = confirmNameList,
                ConfirmNumer = confirmNameList.Count(),
                ReplyList = replyListModel,
                IsDisplayConfirmNow = isDisplayConfirmNow,
                IsDisplayHasConfirmed = isDisplayHasConfirmed
            }.ToJson();

            ViewData["CurrentUser"] = _coreAppService.GetSimpleUserById(CurrentUserId).ToJson();
            ViewData["CurrentTime"] = getEpochForJavascript(DateTime.Now);


            return View();
        }

        //
        // GET: /Message/Inbox
        
        public ActionResult Inbox(Guid? userId)
        {
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }

            var inboxMessages = TopicService.GetMessagesInbox(userId.Value).Result.Select(
                p =>
                {
                    //todo:

                    var hasConfirmed = true;

                    var topic = p.Message;
                    topic.Sender = _coreAppService.GetSimpleUserById(topic.SenderId);
                    topic.Participator = getParticipatorInfo(topic);

                    var item = new
                                   {
                                       Topic = p.Message,
                                       HasConfirmed = hasConfirmed,
                                   };
                    item.Topic.MessageText = item.Topic.MessageText
                        .RemoveHtml()
                        .HtmlEncode()
                        .CutString(50);
                    return item;
                }
                );

            ViewData["Inbox"] = inboxMessages.ToJson();
            return View();
        }


        //
        // GET: /Message/Outbox

        
        public ActionResult Outbox(Guid? userId)
        {
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }

            var outBoxMessages = TopicService.GetMessagesOutbox(userId.Value).Result.Select(
               p =>
               {
                   //todo:
                   var confirmedNumber = p.MessageInbox.Count(confirm=>confirm.ConfirmOn != null);
                   p.Participator = getParticipatorInfo(p);

                   var item = new
                   {
                       Topic = p,
                       ConfirmedNumber = confirmedNumber,
                   };
                   item.Topic.MessageText = item.Topic.MessageText
                       .RemoveHtml()
                       .HtmlEncode()
                       .CutString(50);
                   return item;
               }
               );


            ViewData["Outbox"] = outBoxMessages.ToJson();

            return View();
        }

        #endregion

        #region [Ajax method]


        //
        // GET: /Message/ConfirmMessage

        
        public ActionResult ConfirmMessage(Guid topicId, string target)
        {
            var statusInfo = TopicService.ConfirmMessage(topicId, CurrentUserId);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "您已确认了此信件";
            }

            if (target != "action")
            {
                return RedirectToAction("Show", new { topicId, status = statusInfo.Status, info = statusInfo.Info });
            }

            // target = action的情况
            return Json(statusInfo);

        }


        //
        // POST: /Message/DoSend

        
        [ValidateInput(false)]
        [HttpPost]
        public JsonResult DoSend(string memberString, string messageTitle, string messageText, bool? needConfirm)
        {
            if (memberString == "null")
            {
                memberString = null;
            }

            Guid senderId = CurrentUserId;
            StatusInfo statusInfo;

            if (messageText.RemoveHtml().IsNullOrEmpty())
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, MsgContentRequired);
                return Json(statusInfo, JsonRequestBehavior.AllowGet);
            }

            // 尝试添加一条信件
            var createNewTopicStatusInfo = TopicService.CreateNewTopic(
                    senderId,
                    messageTitle,
                    messageText,
                    needConfirm.GetValueOrDefault(false),
                    memberString);
            var newTopicId = createNewTopicStatusInfo.Result;
            statusInfo = createNewTopicStatusInfo.ToSimpleStatusInfo();

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "创建新的信件完成";
                statusInfo.Data = new { topicId = newTopicId.ToString() };
            }

            return Json(statusInfo);
        }

        //
        // POST: /Message/ReplyTopic

        
        public ActionResult ReplyTopic(Guid topicId, string replyText, bool isReplyToAll)
        {
            StatusInfo statusInfo;

            if (replyText
                  .RemoveHtml().IsNullOrEmpty())
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, ReplyRequired);
                return Json(statusInfo);
            }

            statusInfo = TopicService.ReplyToMessage(CurrentUserId, topicId, topicId, replyText, isReplyToAll);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "回复完成";
            }
            return Json(statusInfo);
        }



        //
        // POST: /Message/ReplySingleMessage

        
        public ActionResult ReplySingleMessage(Guid topicId, Guid messageId, string replyText, bool isReplyToAll)
        {
            StatusInfo statusInfo;

            if (string.IsNullOrEmpty(replyText.RemoveHtml()))
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, ReplyRequired);
                return Json(statusInfo, JsonRequestBehavior.AllowGet);

            }

            statusInfo = TopicService.ReplyToMessage(CurrentUserId, messageId, topicId, replyText, isReplyToAll);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "回复完成";
            }

            return Json(statusInfo, JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region private method
        private ParticipatorsInfo getParticipatorInfo(Topic topic)
        {
            var children = _coreAppService.GetChildrenByMemberString(topic.Memberstring);
            var groupParticipators = new List<Group>();
            var userParticipators = new List<SimpleUser>();
            foreach (var child in children)
            {
                if (child.Value == "user")
                {
                    userParticipators.Add(
                        _coreAppService.GetSimpleUserById(child.Key)
                        );

                }
                else if (child.Value == "group")
                {
                    var dd = _coreAppService.GetGroupById(child.Key);
                    groupParticipators.Add(dd);
                }
            }

            var participator = new ParticipatorsInfo()
            {
                Memberstring = topic.Memberstring,
                AllUserMemebers = _coreAppService.GetAllUsersByMemberString(topic.Memberstring),
                GroupParticipators = groupParticipators,
                UserParticipators = userParticipators,
            };
            return participator;
        }
        #endregion

    }


}
